package com.cap.bts.framework.auth.interceptor;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cap.bts.commonfunc.common.util.UserUtil;
import com.cap.bts.crmdp.dealer.mars.constants.MARSConstants;
import com.cap.bts.crmdp.dealer.mars.service.IMarsConfigService;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.util.ApplicationContextUtil;
import com.cap.bts.framework.usermgnt.domain.User;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 初始化请求信息
 *
 *
 */
public class MarsCutoverHandlerInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(MarsCutoverHandlerInterceptor.class);
    
    private static List<String> CUTOVER_DEALER_ID_LIST = new ArrayList<String>();
    
    private static Long lastLoadDealerIdTime = null;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse response, Object handler) throws Exception {
    	if(req.getRequestURI().endsWith(".js") || req.getRequestURI().endsWith(".css")
                || req.getRequestURI().endsWith(".jpg") || req.getRequestURI().endsWith(".gif")
                || req.getRequestURI().endsWith(".mp3") || req.getRequestURI().endsWith(".woff2")
                || req.getRequestURI().endsWith(".bmp") || req.getRequestURI().endsWith(".htm")
                || req.getRequestURI().endsWith(".png")
                || MARSConstants.checkIsBaseMARSUrl(req.getRequestURI())
            		){
                return true;
         }else if(MARSConstants.checkMARSUrl(req.getRequestURI())){
        	 HttpSession session = req.getSession();
        	 
        	 MARSConstants.MARS_SESSSION_ID_LIST.add(session.getId());
				
        	 logger.info("check MARS SESSION: " + session.getId());
        	 
			 Object flag = session.getAttribute("AUTHORIZE_MARS");
			if (flag == null) {// 未授权访问
				logger.info("check MARS flag ERROR: " + session.getId());
				User user = (User) RequestContextHolder.currentRequestAttributes().getAttribute(
				        "userSession", RequestAttributes.SCOPE_SESSION);
				if(user != null){
					return true;
				}
				logger.info("check MARS user is login ERROR: " + session.getId());
				
				if(MARSConstants.MARS_SESSSION_ID_LIST.contains(session.getId())){
					return true;
				}
				
				logger.info("check MARS SESSION ERROR END, redirect 403 : " + session.getId());
				
				String contextPath = req.getContextPath();
				response.sendRedirect(contextPath + "/common/403.jsp");
				
				return false;
			}else{
				return true;
			}
        	 
         }
    	
    	loadDealerId();
    	
//        User user = UserUtil.getCurrentUser();
        User user = (User) RequestContextHolder.currentRequestAttributes().getAttribute(
		        "userSession", RequestAttributes.SCOPE_SESSION);
        if(user != null){
        	Long dealerId = user.getDealerId();
        	if(CUTOVER_DEALER_ID_LIST.contains(dealerId + "")){
        		
        		String contextPath = req.getContextPath();
        		response.sendRedirect(contextPath + "/common/error.jsp");
        		return false;
        	}
        }
        

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest req, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
    
    public void loadDealerId(){
    	Long nowTime = System.currentTimeMillis();
    	if(lastLoadDealerIdTime == null || nowTime - lastLoadDealerIdTime > 300000){
    		lastLoadDealerIdTime = nowTime;
    		
    		new Thread(){
    			public void run(){
    				try {
    					IMarsConfigService  marsConfigService = (IMarsConfigService) ApplicationContextUtil.getBean("marsConfigServiceImpl");
    					
    					List<Object> idList = marsConfigService.getCutoverDealerIdList();
    					
    					List<String> tempList = new ArrayList<String>();
    					
    					for (Iterator iterator = idList.iterator(); iterator.hasNext();) {
    						Object long1 = (Object) iterator.next();
    						if(long1 != null){
    							String dealearId = long1.toString();
    							if(StringUtils.isNotBlank(dealearId)){
    								tempList.add(dealearId);
    							}
    						}
    					}
    					
    					CUTOVER_DEALER_ID_LIST = tempList;
    				} catch (AppException e) {
    					logger.error("", e);
    				}
    			}
    		}.start();
    	}
    	
    	
    	
    }





}
